import React, { useCallback, useState } from 'react';
import { Upload, CheckCircle, AlertCircle, Loader2, FileText, Trash2 } from 'lucide-react';
import { useProofMapper } from '@/contexts/ProofMapper';
import { useFileUpload } from './hooks/useFileUpload';
import { useBusiness } from '@/stores/useBusinessStore';
import { showMessage } from '@/components/common/MessageTip';
import { getPdfPageCount } from './utils/pdfUtils';
import DeleteConfirmModal from '@/components/common/DeleteConfirmModal';
import type { UploadedFile, PageRange } from '@/types/ProofMapper';

interface FileUploadProps {
  className?: string;
  // 选择历史版本后跳到第二步
  onUseVersion?: () => void;
}

const FileUpload: React.FC<FileUploadProps> = ({ className = '', onUseVersion }) => {
  const { 
    currentFile, 
    addFile, 
    updateFileStatus, 
    versionList,
    loadingVersions,
    loadVersionList,
    loadVersionById,
    deleteVersion,
    applySnapshot 
  } = useProofMapper();
  const { selectedBusiness } = useBusiness();
  const { uploadFile, uploading } = useFileUpload();

  // 页面范围状态
  const [dragActive, setDragActive] = useState(false);
  const [showPageRangeDialog, setShowPageRangeDialog] = useState(false);
  const [pageRange, setPageRange] = useState<PageRange>({
    startPage: 1,
    endPage: 1,
    totalPages: 1,
    mode: 'all'
  });

  // 版本管理展示开关
  const [showVersionPanel, setShowVersionPanel] = useState(true);

  // 删除确认弹窗
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [versionToDelete, setVersionToDelete] = useState<{ id: string; name: string } | null>(null);

  // 获取版本列表
  React.useEffect(() => {
    const fetchVersions = async () => {
      if (!selectedBusiness) return;
      
      try {
        await loadVersionList(selectedBusiness.assessmentType);
      } catch (error) {
        console.error('获取版本列表失败:', error);
      }
    };

    fetchVersions();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedBusiness?.assessmentType]);

  // 加载指定版本并跳转第二步
  const handleLoadVersion = useCallback(async (snapshotId: string, versionName: string) => {
    if (!selectedBusiness) {
      showMessage('warning', '请先选择业务类型');
      return;
    }
    
    const snapshot = await loadVersionById(selectedBusiness.assessmentType, snapshotId);
    if (!snapshot) {
      showMessage('warning', '加载版本失败');
      return;
    }
    
    applySnapshot(snapshot);
    showMessage('success', `已加载版本：${versionName}`);
    onUseVersion?.();
  }, [applySnapshot, loadVersionById, onUseVersion, selectedBusiness]);

  // 打开删除确认弹窗
  const handleDeleteClick = useCallback((versionId: string, versionName: string) => {
    setVersionToDelete({ id: versionId, name: versionName });
    setShowDeleteConfirm(true);
  }, []);

  // 确认删除版本
  const handleConfirmDelete = useCallback(async () => {
    if (!versionToDelete || !selectedBusiness) return;
    
    const ok = await deleteVersion(versionToDelete.id);
    if (ok) {
      // 刷新版本列表
      await loadVersionList(selectedBusiness.assessmentType);
    }
    
    setShowDeleteConfirm(false);
    setVersionToDelete(null);
  }, [versionToDelete, selectedBusiness, deleteVersion, loadVersionList]);

  // 处理文件选择
  const handleFileSelect = useCallback(async (files: FileList | null) => {
    if (!files || files.length === 0) return;
    const file = files[0];

    // 验证文件类型
    if (file.type !== 'application/pdf') {
      showMessage('error', '请上传PDF格式的文件');
      return;
    }

    // 验证文件大小 (限制为50MB)
    const maxSize = 50 * 1024 * 1024; // 50MB
    if (file.size > maxSize) {
      showMessage('error', '文件大小不能超过50MB');
      return;
    }

    let tempFileId: string | null = null;
    try {
      // 获取 PDF 总页数
      const totalPages = await getPdfPageCount(file);

      // 创建临时文件对象
      tempFileId = `file-${Date.now()}`;
      const tempFile: UploadedFile = {
        id: tempFileId,
        name: file.name,
        size: file.size,
        type: file.type,
        status: 'idle',
        uploaded_at: new Date().toISOString()
      };

      // 添加文件到状态
      addFile(tempFile);
      
      // 更新页面范围状态
      setPageRange(prev => ({
        ...prev,
        endPage: totalPages,
        totalPages,
        mode: 'all'
      }));

      // 显示页面范围选择对话框
      setShowPageRangeDialog(true);
    } catch (error) {
      showMessage('error', '获取PDF页数失败，请检查文件是否有效');
    }
  }, [addFile]);

  // 处理拖拽事件
  const handleDrag = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      handleFileSelect(e.dataTransfer.files);
    }
  }, [handleFileSelect]);

  // 处理点击选择文件
  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    handleFileSelect(e.target.files);
  };

  // 获取状态图标
  const getStatusIcon = (status: UploadedFile['status']) => {
    switch (status) {
      case 'uploading':
        return <Loader2 className="h-4 w-4 animate-spin text-primary" />;
      case 'parsing':
        return <Loader2 className="h-4 w-4 animate-spin text-primary" />;
      case 'completed':
        return <CheckCircle className="h-4 w-4 text-green-500" />;
      case 'error':
        return <AlertCircle className="h-4 w-4 text-red-500" />;
      default:
        return <FileText className="h-4 w-4 text-muted-foreground" />;
    }
  };

  // 获取状态文本
  const getStatusText = (status: UploadedFile['status'], progress?: number) => {
    switch (status) {
      case 'uploading':
        return `正在上传... ${progress || 0}%`;
      case 'parsing':
        return `正在解析... ${progress || 0}%`;
      case 'completed':
        return '已提取评估项和查验点';
      case 'error':
        return '上传失败';
      default:
        return '待上传';
    }
  };

  // 格式化文件大小
  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 处理页面范围选择
  const handlePageRangeSubmit = useCallback(async () => {
    if (currentFile) {
      try {
        // 更新文件的页面范围
        updateFileStatus(currentFile.id, currentFile.status);

        // 获取原始文件对象
        const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
        if (!fileInput || !fileInput.files || !fileInput.files[0]) {
          throw new Error('文件不存在，请重新选择');
        }

        // 开始上传和处理文件
        setShowPageRangeDialog(false);
        const success = await uploadFile(currentFile.id, fileInput.files[0], pageRange);
        
        if (!success) {
          showMessage('error', '文件处理失败');
        } else {
          // 解析成功：进入步骤二
          onUseVersion?.();
        }
      } catch (error) {
        showMessage('error', error instanceof Error ? error.message : '文件处理失败');
        setShowPageRangeDialog(false);
      }
    }
  }, [pageRange, currentFile, uploadFile, updateFileStatus]);

  // 从后端按业务系统评估类型加载历史版本（已移至页面自动加载）
  // 页面加载时会自动调用loadSnapshot获取历史版本

  // 处理页面范围模式切换
  const handlePageRangeModeChange = useCallback((mode: 'all' | 'range') => {
    setPageRange(prev => ({
      ...prev,
      mode,
      startPage: 1,
      endPage: mode === 'all' ? (prev.totalPages || prev.endPage) : prev.endPage
    }));
  }, []);

  return (
    <div className={`space-y-6 ${className}`}>
      {/* 上传区域 */}
      <div className="bg-white/80 dark:bg-card backdrop-blur-sm rounded-lg border border-border p-6">
        <div className="flex items-center gap-3 mb-4">
          <div className="flex items-center justify-center w-10 h-10 bg-primary/10 rounded-lg">
            <Upload className="h-5 w-5 text-primary" />
          </div>
          <div>
            <h2 className="text-lg font-semibold text-foreground">文件上传区</h2>
            <p className="text-sm text-muted-foreground">
              上传安全评估指南或业务系统资料（PDF格式）
            </p>
          </div>
          <div className="ml-auto">
            <button
              type="button"
              className="text-sm text-primary hover:bg-primary/10 rounded-md px-3 py-2"
              onClick={() => setShowVersionPanel(v => !v)}
            >
              {showVersionPanel ? '隐藏版本管理' : '显示版本管理'}
            </button>
          </div>
        </div>

        {/* 拖拽上传区域 */}
        <div
          className={`
            relative border-2 border-dashed rounded-lg p-8 text-center transition-colors
            ${dragActive 
              ? 'border-primary bg-primary/5' 
              : 'border-border hover:border-primary/50'
            }
          `}
          onDragEnter={handleDrag}
          onDragLeave={handleDrag}
          onDragOver={handleDrag}
          onDrop={handleDrop}
        >
          <input
            type="file"
            accept=".pdf"
            onChange={handleFileInputChange}
            className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
            disabled={uploading}
          />
          
          <div className="space-y-4">
            <div className="flex justify-center">
              <Upload className="h-12 w-12 text-muted-foreground" />
            </div>
            <div>
              <p className="text-lg font-medium text-foreground mb-1">
                点击或拖拽上传PDF文件
              </p>
              <p className="text-sm text-muted-foreground">
                支持最大50MB的PDF文件
              </p>
            </div>
            <button
              type="button"
              className="inline-flex items-center px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              disabled={uploading}
            >
              选择文件
            </button>
          </div>
        </div>
      </div>

      {/* 历史版本列表 */}
      {showVersionPanel && (
        <div className="bg-white/80 dark:bg-card backdrop-blur-sm rounded-lg border border-border p-6">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <span className="text-base font-semibold text-foreground">历史版本</span>
              <span className="text-xs text-muted-foreground">
                共 {versionList.length} 个版本 · 选择版本直接进入调整步骤
              </span>
            </div>
          </div>

          {loadingVersions ? (
            <div className="p-4 text-sm text-muted-foreground bg-muted/30 rounded-lg">
              加载中...
            </div>
          ) : versionList.length === 0 ? (
            <div className="p-4 text-sm text-muted-foreground bg-muted/30 rounded-lg border border-dashed border-border">
              暂无历史版本，上传文件解析后可保存版本
            </div>
          ) : (
            <div className="space-y-2 max-h-64 overflow-y-auto">
              {versionList.map((version) => (
                <div
                  key={version.id}
                  className="flex items-center justify-between p-3 bg-muted/20 rounded-lg border border-border hover:bg-muted/30 transition-colors"
                >
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-medium text-foreground truncate">
                      {version.name}
                    </div>
                    <div className="text-xs text-muted-foreground mt-1">
                      {new Date(version.saved_at).toLocaleString()} · {version.items_count} 项 · {version.modules_count} 模块
                    </div>
                  </div>
                  <div className="flex items-center gap-2 ml-3">
                    <button
                      onClick={() => handleLoadVersion(version.id, version.name)}
                      className="px-3 py-1.5 text-sm bg-primary text-primary-foreground rounded-md hover:bg-primary/90 whitespace-nowrap"
                    >
                      加载
                    </button>
                    <button
                      onClick={() => handleDeleteClick(version.id, version.name)}
                      className="p-1.5 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-md transition-colors"
                      title="删除版本"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* 文件解析进度条 */}
      {currentFile && (
        <div className="bg-white/80 dark:bg-card backdrop-blur-sm rounded-lg border border-border p-6">
          <div className="flex items-center gap-3 mb-4">
            <div className="flex items-center justify-center w-10 h-10 bg-primary/10 rounded-lg">
              <FileText className="h-5 w-5 text-primary" />
            </div>
            <div className="flex-1">
              <h3 className="text-lg font-semibold text-foreground">文件解析进度</h3>
              <p className="text-sm text-muted-foreground">
                {currentFile.name} · {formatFileSize(currentFile.size)}
                {currentFile.pageRange && (
                  <span className="ml-2">
                    · {currentFile.pageRange.mode === 'all' 
                      ? '全部页面' 
                      : `第${currentFile.pageRange.startPage}-${currentFile.pageRange.endPage}页`}
                  </span>
                )}
              </p>
            </div>
            <div className="flex-shrink-0">
              {getStatusIcon(currentFile.status)}
            </div>
          </div>
          
          {/* 进度条 */}
          <div className="space-y-3">
            <div className="flex items-center justify-between text-sm">
              <span className="text-muted-foreground">
                {getStatusText(currentFile.status, currentFile.progress)}
              </span>
              <span className="text-muted-foreground">
                {currentFile.progress !== undefined ? `${currentFile.progress}%` : ''}
              </span>
            </div>
            
            {(currentFile.status === 'uploading' || currentFile.status === 'parsing') && (
              <div className="bg-muted rounded-full h-2">
                <div
                  className="h-2 rounded-full transition-all duration-300 bg-primary"
                  style={{ width: `${currentFile.progress || 0}%` }}
                />
              </div>
            )}
            
            {currentFile.status === 'completed' && (
              <div className="bg-green-100 dark:bg-green-900/20 rounded-lg p-3">
                <div className="flex items-center gap-2 text-sm text-green-700 dark:text-green-300">
                  <CheckCircle className="h-4 w-4" />
                  <span>文件解析完成，已提取评估项和查验点</span>
                </div>
              </div>
            )}
            
            {currentFile.status === 'error' && (
              <div className="bg-red-100 dark:bg-red-900/20 rounded-lg p-3">
                <div className="flex items-center gap-2 text-sm text-red-700 dark:text-red-300">
                  <AlertCircle className="h-4 w-4" />
                  <span>文件处理失败，请重试</span>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* 页面范围选择对话框 */}
      {showPageRangeDialog && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-card rounded-lg p-6 w-[480px] space-y-6">
            <div className="flex items-center gap-3">
              <div className="flex items-center justify-center w-10 h-10 bg-primary/10 rounded-lg">
                <FileText className="h-5 w-5 text-primary" />
              </div>
              <div>
                <h2 className="text-lg font-semibold text-foreground">选择解析页面范围</h2>
                <p className="text-sm text-muted-foreground">
                  请选择需要解析的PDF页面范围
                </p>
              </div>
            </div>

            <div className="space-y-4">
              {/* 选择模式 */}
              <div className="flex gap-4">
                <button
                  type="button"
                  className={`flex-1 p-4 rounded-lg border ${
                    pageRange.mode === 'all'
                      ? 'border-primary bg-primary/5 text-primary'
                      : 'border-border hover:border-primary/50'
                  }`}
                  onClick={() => handlePageRangeModeChange('all')}
                >
                  <h3 className="font-medium mb-1">解析全部页面</h3>
                  <p className="text-sm text-muted-foreground">
                    将解析文档中的所有页面
                  </p>
                </button>
                <button
                  type="button"
                  className={`flex-1 p-4 rounded-lg border ${
                    pageRange.mode === 'range'
                      ? 'border-primary bg-primary/5 text-primary'
                      : 'border-border hover:border-primary/50'
                  }`}
                  onClick={() => handlePageRangeModeChange('range')}
                >
                  <h3 className="font-medium mb-1">选择页面范围</h3>
                  <p className="text-sm text-muted-foreground">
                    指定需要解析的页面范围
                  </p>
                </button>
              </div>

              {/* 页面范围输入 */}
              {pageRange.mode === 'range' && (
                <div className="flex items-center gap-3">
                  <div className="flex-1">
                    <label className="block text-sm font-medium text-foreground mb-1">
                      起始页
                    </label>
                    <input
                      type="number"
                      min="1"
                      value={pageRange.startPage}
                      onChange={(e) => setPageRange(prev => ({
                        ...prev,
                        startPage: Math.max(1, parseInt(e.target.value) || 1)
                      }))}
                      className="w-full px-3 py-2 rounded-md border border-border bg-background text-foreground"
                    />
                  </div>
                  <div className="flex items-center pt-6">
                    <span className="text-muted-foreground">至</span>
                  </div>
                  <div className="flex-1">
                    <label className="block text-sm font-medium text-foreground mb-1">
                      结束页
                    </label>
                    <input
                      type="number"
                      min={pageRange.startPage}
                      value={pageRange.endPage}
                      onChange={(e) => setPageRange(prev => ({
                        ...prev,
                        endPage: Math.max(prev.startPage, parseInt(e.target.value) || prev.startPage)
                      }))}
                      className="w-full px-3 py-2 rounded-md border border-border bg-background text-foreground"
                    />
                  </div>
                </div>
              )}
            </div>

            <div className="flex justify-end gap-3 pt-2">
              <button
                type="button"
                className="px-4 py-2 rounded-md hover:bg-muted transition-colors"
                onClick={() => setShowPageRangeDialog(false)}
              >
                取消
              </button>
              <button
                type="button"
                className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors"
                onClick={handlePageRangeSubmit}
              >
                确认并开始解析
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 删除确认弹窗 */}
      <DeleteConfirmModal
        isOpen={showDeleteConfirm}
        onClose={() => {
          setShowDeleteConfirm(false);
          setVersionToDelete(null);
        }}
        onConfirm={handleConfirmDelete}
        title="确认删除版本"
        itemName={versionToDelete?.name || ''}
        message="您确定要删除以下版本吗？"
        confirmText="确认删除"
        cancelText="取消"
        dangerMessage="注意：此操作不可撤销，删除后版本数据将无法恢复。"
      />
    </div>
  );
};

export default FileUpload;
